﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Text;

using com.vs.General;
using com.vs.DataAccess;
using com.vs.DataAccess.DO;
using com.vs.Inventory.BL;

namespace com.vs.Receiving.BL
{
    public class ReceiptManager
    {
        public string SaveReceiptHdr(Session sess, ReceiptHeaderDO rcpHdrDO)
        {
            string stErr = null;

            try
            {
                if (rcpHdrDO.INTERNAL_RECEIPT_NUM > 0)
                {
                    rcpHdrDO.Update(sess);
                    stErr = "" + rcpHdrDO.INTERNAL_RECEIPT_NUM;
                }
                else
                {
                    //检查是否存在相同单号的出库单
                    if (this.DoesReceiptExist(sess, rcpHdrDO.WAREHOUSE, rcpHdrDO.RECEIPT_ID))
                        return MessageManager.MSG_RCP_017;//错误：相同单号的入库单已经存在

                    stErr = "" + rcpHdrDO.Insert(sess);
                    if (StringManager.IsEmpty(stErr))
                        HistoryManager.SaveProcessHistory(sess, 
                            HistoryManager.ProcessType.iShipment, 
                            HistoryManager.Condition.iNew, 
                            "入库单创建成功", 
                            rcpHdrDO.RECEIPT_ID, sess.User, null, null);
                }

                return stErr;
            }
            catch (Exception e)
            {
                ExceptionManager.LogException(sess, e);
                return MessageManager.MSG_GEN_000 + e.Message;
            }
        }

        public string DeleteReceipt(Session sess, int iIntRcpNum)
        {
            DataHelper helper = null;

            try
            {
                helper = new DataHelper(sess);
                return helper.GetString(CommandType.StoredProcedure, "RCP_DReceiptHeader", new IDataParameter[]{
                    DataHelper.BuildParameter(sess, "@INTERNAL_RECEIPT_NUM", iIntRcpNum)});
            }
            catch (Exception e)
            {
                ExceptionManager.LogException(sess, e);
                return MessageManager.MSG_GEN_000 + e.Message;
            }
            finally
            {
                if (helper != null)
                    helper.Dispose();
            }
        }

        public string SaveReceiptDtl(Session sess, ReceiptDetailDO rcpDtlDO)
        {
            int iBaseQty = 0;
            string stBaseUM = null;

            try
            {
                //如果客户在前端录入的不是基本数量单位，在这里我们要做转换
                stBaseUM = ItemManager.GetBaseUM(sess, rcpDtlDO.ITEM, rcpDtlDO.COMPANY);
                if (StringManager.IsErrorMessage(stBaseUM))
                    return stBaseUM;
                if (!StringManager.Equals(stBaseUM, rcpDtlDO.QUANTITY_UM))
                {
                    rcpDtlDO.QUANTITY_UM = stBaseUM;

                    //1. 计算总数量
                    iBaseQty = ItemManager.GetBaseQty(sess, rcpDtlDO.ITEM, rcpDtlDO.COMPANY, rcpDtlDO.TOTAL_QTY, rcpDtlDO.QUANTITY_UM);
                    rcpDtlDO.TOTAL_QTY = iBaseQty;

                    //2. 计算待收数量
                    rcpDtlDO.OPEN_QTY = ItemManager.GetBaseQty(sess, rcpDtlDO.ITEM, rcpDtlDO.COMPANY, rcpDtlDO.OPEN_QTY, rcpDtlDO.QUANTITY_UM);
                }

                if (rcpDtlDO.INTERNAL_RECEIPT_LINE_NUM > 0)
                {
                    rcpDtlDO.Update(sess);
                    return "" + rcpDtlDO.INTERNAL_RECEIPT_LINE_NUM;
                }
                else
                {
                    return "" + rcpDtlDO.Insert(sess);
                }
            }
            catch (Exception e)
            {
                ExceptionManager.LogException(sess, e);
                return MessageManager.MSG_GEN_000 + e.Message;
            }
            finally
            {
            }
        }

        public string DeleteReceiptDtl(Session sess, int iIntRcpLnNum)
        {
            DataHelper helper = null;

            try
            {
                helper = new DataHelper(sess);
                return helper.GetString(CommandType.StoredProcedure, "RCP_DReceiptDetail", new IDataParameter[]{
                    DataHelper.BuildParameter(sess, "@INTERNAL_RECEIPT_LINE_NUM", iIntRcpLnNum)});
            }
            catch (Exception e)
            {
                return MessageManager.MSG_GEN_000 + e.Message;
            }
            finally
            {
                if (helper != null)
                    helper.Dispose();
            }
        }

        public string GetReceivingDock(Session sess, int iIntRcpNum)
        {
            DataHelper helper = null;
            string stRecvDock = null;
            DataTable dt = null;
            string stSQL = "SELECT RECV_DOCK, WAREHOUSE FROM RECEIPT_HEADER WHERE INTERNAL_RECEIPT_NUM = @INTERNAL_RECEIPT_NUM";
            LocationManager locMgr = null;
            string stWarehouse = null;

            try
            {
	            helper = new DataHelper(sess);
                dt = helper.GetTable(CommandType.Text, stSQL, new IDataParameter[] { 
				            DataHelper.BuildParameter(sess, "@INTERNAL_RECEIPT_NUM", iIntRcpNum)
			            });
                
                if (!DataManager.IsEmpty(dt))
                {
                    stRecvDock = DataManager.GetString(dt.Rows[0], "RECV_DOCK");
                    if (!StringManager.IsEmpty(stRecvDock))
                        return stRecvDock;

                    stWarehouse = DataManager.GetString(dt.Rows[0], "WAREHOUSE");
                    
                    locMgr = new LocationManager();
                    return locMgr.GetDefaultRecvDock(sess, stWarehouse);
                }
                else
                    return null;
            }
            catch (Exception e)
            {
	            ExceptionManager.LogException(sess, e);
	            return null;
            }
            finally
            {
	            if (helper != null)
		            helper.Dispose();
            }
        }

        public string GenReceiptFromPO(Session sess, int iIntPONum, string stReceiptID, int[] arLineNum, int[] arLineQty)
        {
            POManager mgr = null;
            string stErr = null;
            int iReceiptNum = 0;
            StringBuilder sbErr = null;

            try
            {
                mgr = new POManager();
                stErr = mgr.GenerateReceiptHeader(sess, iIntPONum, stReceiptID);
                if (StringManager.IsErrorMessage(stErr))
                    return stErr;
                else
                    iReceiptNum = Convert.ToInt32(stErr);

                int iLen = arLineNum.Length;
                sbErr = new StringBuilder();

                for (int i = 0; i < iLen; i++)
                {
                    stErr = mgr.GenerateReceiptDetail(sess, arLineNum[i], stReceiptID, iReceiptNum, arLineQty[i]);
                    if (StringManager.IsErrorMessage(stErr))
                    {
                        sbErr.AppendLine(stErr);
                        continue;
                    }
                }
                if (!StringManager.IsEmpty(sbErr))
                    return sbErr.ToString();
                else
                    return null;

            }
            catch (Exception e)
            {
                ExceptionManager.LogException(sess, e);
                return MessageManager.MSG_GEN_000 + e.Message;
            }
            finally
            {
            }
        }

        public DataTable GetReceiptHdrsByQFCri(Session sess, List<KeyValuePair<string, KeyValuePair<string, object>>> dcParam, string stOrderBy, ref string stError)
        {
            DataHelper helper = null;
            StringBuilder sbSQL = null;
            int i = 0;
            IDataParameter[] pars = null;

            try
            {
                sbSQL = new StringBuilder(" SELECT DISTINCT RH.* FROM RECEIPT_HEADER RH LEFT JOIN RECEIPT_DETAIL RD ON RH.INTERNAL_RECEIPT_NUM = RD.INTERNAL_RECEIPT_NUM WHERE 1=1 ");
                helper = new DataHelper(sess);
                pars = new IDataParameter[dcParam.Count];
                foreach (KeyValuePair<string, KeyValuePair<string, object>> de in dcParam)
                {
                    sbSQL.Append(" AND ").Append(de.Key.ToString()).Append(de.Value.Key).Append("@Value").Append(i);
                    pars[i] = new SqlParameter("@Value" + i, de.Value.Value);
                    i++;
                }

                if (!StringManager.IsEmpty(stOrderBy))
                {
                    sbSQL.Append(stOrderBy);
                }
                return helper.GetTable(CommandType.Text, sbSQL.ToString(), pars);
            }
            catch (Exception e)
            {
                ExceptionManager.LogException(sess, e);
                stError = MessageManager.MSG_GEN_000 + e.Message;
                return null;
            }
            finally
            {
                if (helper != null)
                    helper.Dispose();
            }
        }

        public string UpdateReceiptStatus(Session sess, int iRecNum)
        {
            DataHelper helper = null;
            string stSQL = "RCP_UReceiptStatus";

            try
            {
                //更新行数量
                //更新整单状态
                helper = new DataHelper(sess);
                helper.Update(CommandType.StoredProcedure, stSQL, new IDataParameter[] { 
				            DataHelper.BuildParameter(sess, "@INTERNAL_RECEIPT_NUM", iRecNum)
                    });
                return null;
            }
            catch (Exception e)
            {
                ExceptionManager.LogException(sess, e);
                return MessageManager.MSG_GEN_000 + e.Message;
            }
            finally
            {
                if (helper != null)
                    helper.Dispose();
            }
        }

        public string UpdateReceiptStatus(Session sess, int iRecNum, int iLeadingSts, int iTrailingSts)
        {
            ReceiptHeaderDO rhDO = null;
            Dictionary<string, object> dcParam = null;

            try
            {
                rhDO = ReceiptHeaderDO.GetModelByPK(sess, iRecNum);
                if (rhDO == null)
                    return MessageManager.MSG_RCP_013;

                dcParam = new Dictionary<string, object>();
                if (rhDO.LEADING_STS < iLeadingSts)
                    dcParam.Add("LEADING_STS", iLeadingSts);
                if (rhDO.TRAILING_STS < iTrailingSts)
                    dcParam.Add("TRAILIN_STS", iTrailingSts);

                if (dcParam.Count > 0)
                {
                    rhDO.Update(sess, dcParam);
                }
                return null;
            }
            catch (Exception e)
            {
                ExceptionManager.LogException(sess, e);
                return MessageManager.MSG_GEN_000 + e.Message;
            }
            finally
            {
            }
        }

        public bool DoesReceiptExist(Session sess, string stWarehosue, string stReceiptID)
        {
            string stSQL = null;
            DataHelper helper = null;
            int iCnt = 0;

            try
            {
                stSQL = " SELECT COUNT(1) FROM RECEIPT_HEADER WHERE RECEIPT_ID = @RECEIPT_ID AND WAREHOUSE = @WAREHOUSE ";
                    helper = new DataHelper(sess);

                    iCnt = helper.GetInt(CommandType.Text, stSQL, new IDataParameter[]{
                        DataHelper.BuildParameter(sess, "@RECEIPT_ID", stReceiptID),
                        DataHelper.BuildParameter(sess, "@WAREHOUSE", stWarehosue)});

                    return (iCnt > 0);
            }
            catch (Exception e)
            {
                ExceptionManager.LogException(sess, e);
                return false;
            }
            finally
            {
                if (helper != null)
                    helper.Dispose();
            }
        }
    }
}
